import datetime
import jwt
from django.conf.global_settings import SECRET_KEY
from rest_framework.authentication import BaseAuthentication


# 生成Token
def create_token(payload, timeout):
    header = {
        "alg": "HS256",
        "typ": "JWT"
    }

    payload = payload
    payload["exp"] = datetime.datetime.utcnow() + datetime.timedelta(minutes=1000)

    result = jwt.encode(headers=header, payload=payload, key=SECRET_KEY, algorithm='HS256')
    return result

# 验证Token
def get_payload(token):
    result = {"status": False, "payload": None, "error": None}
    try :
        payload = jwt.decode(jwt=token, key=SECRET_KEY, algorithms=['HS256'])
        result["status"] = True
        result['payload'] = payload
    except jwt.exceptions.ExpiredSignatureError:
        result['error'] = 'Token已经过期了'
    except jwt.exceptions.InvalidSignatureError:
        result['error'] = 'Token不合法'
    except jwt.exceptions.DecodeError:
        result['error'] = 'Token不能通过验证'
    return result

# JWT，URL参数传递Token的身份验证类
class JWTURLParamAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.GET.get('token')
        token_data = get_payload(token)
        print(token_data)
        return token_data, token
        # 这里必选按照
        # {'status': True, 'payload': {'email': '006@QQ.com', 'exp': 1712306747}, 'error': None}
        # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IjAwNkBRUS5jb20iLCJleHAiOjE3MTIzMDY3NDd9.uq3kYZaksxVNocq6rzYk2Fb8xb6e4PQ84fV6GKed3Es
        # 这样的的形式返回，本别对应 requset.user 和 requset.auth


# JWT，Header传递Token的身份验证类
class JWTHeaderAuthentication(BaseAuthentication):
    def authenticate(self, request):
        print(request.META)
        token = request.META.get('HTTP_TOKEN')
        if(token == None):
            token = request.META.get('HTTP_AUTHORIZAYION')
        print(token)
        payload = get_payload(token)
        print(payload)
        return payload, token